package com.jushu.storbox.actions;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IAlbumFolderDao;
import com.jushu.storbox.entities.AbsContainer;
import com.jushu.storbox.entities.AlbumEntity;
import com.jushu.storbox.entities.AlbumFolderInfo;
import com.jushu.storbox.util.DeviceUtil;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class AlbumContext {

	public final static String ALBUM_ATTRIBUTE_PREFERENCES = "album_catch_attribute";

	private AlbumContainer albumContainer = new AlbumContainer();

	IAlbumFolderDao albumFolderdao = null;
	String currentUserId = ShareDriveApplication.getInstance().getWnerID();

	public AlbumContext(Context context) {
		albumFolderdao = DAOFactory.instance(context).getAlbumFolderDao();
	}

	public HashMap<String, File> scanAllMadieFileMap(Context context) {
		HashMap<String, File> madieFileMap = new HashMap<String, File>();
		
		Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver mContentResolver = context.getContentResolver();

		String selection = null;
		String[] selectionArgs = context.getResources().getStringArray(
				R.array.SUFFIX_PIC_MIME);
		if (null != selectionArgs && selectionArgs.length > 0) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < selectionArgs.length; i++) {
				sb.append(MediaStore.Images.Media.MIME_TYPE + "=? or ");
			}
			int len = sb.length();
			sb.delete(len - 4, len - 1);
			selection = sb.toString();
		}
		Cursor mCursor = mContentResolver.query(mImageUri, null, selection,
				selectionArgs, MediaStore.Images.Media.DISPLAY_NAME);
		if(mCursor != null) {
			while (mCursor.moveToNext()) {
				String path = mCursor.getString(mCursor
						.getColumnIndex(MediaStore.Images.Media.DATA));
				File mediaFile = new File(path);
				if (!mediaFile.isFile() || !mediaFile.exists() || 0 >= mediaFile.length()) {
					continue;
				}
				madieFileMap.put(mediaFile.getAbsolutePath(), mediaFile);
			}
			mCursor.close();
		}

		return madieFileMap;
	}
	
	public List<AlbumEntity> getAlbumList(Context context) {

		albumContainer.clear();
		Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver mContentResolver = context.getContentResolver();

		String selection = null;
		String[] selectionArgs = context.getResources().getStringArray(
				R.array.SUFFIX_PIC_MIME);
		if (null != selectionArgs && selectionArgs.length > 0) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < selectionArgs.length; i++) {
				sb.append(MediaStore.Images.Media.MIME_TYPE + "=? or ");
			}
			int len = sb.length();
			sb.delete(len - 4, len - 1);
			selection = sb.toString();
		}
		Cursor mCursor = mContentResolver.query(mImageUri, null, selection,
				selectionArgs, MediaStore.Images.Media.DISPLAY_NAME);
		while (mCursor.moveToNext()) {
			String path = mCursor.getString(mCursor
					.getColumnIndex(MediaStore.Images.Media.DATA));
			File file = new File(path);
			if (!file.exists() || 0 >= file.length()) {
				continue;
			}
			File pictrueFile = new File(path);
			String parentPath;
			try {
				parentPath = pictrueFile.getParentFile().getCanonicalPath();
				albumContainer.put(parentPath, pictrueFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		mCursor.close();

		return albumContainer.getListedData();
	}

	public boolean saveAlbumEntity(Context context) {
		boolean haveRecored = false;
		
		//clear albumfolder infomation before resave albumfolder
		List<AlbumFolderInfo> oldAlbumFolderList = albumFolderdao.getAlbumFolders(currentUserId);
		albumFolderdao.clearByUserId(currentUserId);
		
		Iterator<AlbumEntity> it = albumContainer.getListedData().iterator();
		while (it.hasNext()) {
			AlbumEntity en = it.next();
			if (en.isSelected()) {
				haveRecored = true;
				AlbumFolderInfo albumFolder = new AlbumFolderInfo();
				albumFolder.setOwnerBy(currentUserId);
				albumFolder.setFolderPath(en.getParent().getAbsolutePath());
				albumFolder.setFolderName(en.getParent().getName());
				albumFolder.setContentCreateAt(en.getParent().lastModified());
				albumFolderdao.insertAlbumFolder(albumFolder);
			}
		}
		
		List<AlbumFolderInfo> newAlbumFolderList = albumFolderdao.getAlbumFolders(currentUserId);
		newAlbumFolderList.retainAll(oldAlbumFolderList);
		for(AlbumFolderInfo info : newAlbumFolderList) {
			int index = oldAlbumFolderList.indexOf(info);
			AlbumFolderInfo oldInfo = oldAlbumFolderList.get(index);
			DAOFactory.instance(context).getAlbumFolderDao().updateAlumbFolderInfo(oldInfo);
		}
		
		oldAlbumFolderList.removeAll(newAlbumFolderList);
		for(AlbumFolderInfo info : oldAlbumFolderList) {
			DAOFactory.instance(context).getAlbumDao().deleteAllAlbumFilesByFolder(info.getFolderPath());
		}
		
		if (!haveRecored) {
			return false;
		} else {
			return true;
		}
	}

	private class AlbumContainer extends
			AbsContainer<String, AlbumEntity, File> {

		Set<String> selfAlbum = new HashSet<String>();

		public AlbumContainer() {
			// selfConfig.add("");
		}

		@Override
		protected boolean elementFilter(String key) {
			if (selfAlbum.contains(key)) {
				return true;
			}
			return super.elementFilter(key);
		}

		@Override
		protected AlbumEntity makeContainer(String key) {
			return new AlbumEntity();
		}

		@Override
		protected int computContainerIndex(String key) {
			File cameraFolder = DeviceUtil.instance().getCameraFolder();
			if (cameraFolder != null
					&& key.equals(cameraFolder.getAbsolutePath())) {
				return 0;
			}
			return super.computContainerIndex(key);
		}

		@Override
		protected void addValueToContainer(String key, AlbumEntity container,
				File value) {
			if (container == null) {
				return;
			}
			container.addChild(0, value);
			if (container.getParent() == null) {
				container.setParent(value.getParentFile());
			}
			if (StringUtil.isNotBlank(key)) {
				AlbumFolderInfo tempAlbumFolder = albumFolderdao.getAlbumFolder(currentUserId, key);
				if(tempAlbumFolder != null) {
					container.setSelected(true);
				}
			}
		}
	}

}
